package org.smart4j.framework.helper;

import org.smart4j.framework.util.ReflectionUtil;

import java.util.HashMap;
import java.util.Set;

/**
 * Bean 助手类
 * @author luoyong
 * @date 2018-11-19下午 7:21
 */
public class BeanHelper {

    /**
     * 定义bean映射(用于存放bean类于bean实例的映射关系)
     */
    private static final HashMap<Class<?>,Object> BEAN_MAP = new HashMap<Class<?>, Object>(16);


    static {
        Set<Class<?>> beanClassSet = ClassHelper.getBeanClassSet();
        for (Class<?> cls : beanClassSet){
            Object instance = ReflectionUtil.newInstance(cls);
            BEAN_MAP.put(cls,instance);
        }

    }

    /**
     * 获取bean映射
     *
     */
    public static HashMap<Class<?>,Object> getBeanMap(){
        return BEAN_MAP;
    }


    /**
     * 获取bean实例
     * @param cls class对象
     * @param <T> bean实例的泛型
     * @return bean实例
     */
    public static <T> T getBean(Class<T> cls){
        if (!BEAN_MAP.containsKey(cls)){
            throw new RuntimeException("can not get bean by class:"+cls);
        }
        return  (T) BEAN_MAP.get(cls);

    }


}
